/*
 *	Copyright © 2013 Changsha Shishuo Network Technology Co., Ltd. All rights reserved.
 *	长沙市师说网络科技有限公司 版权所有
 *	http://www.shishuo.com
 */

package com.hlingsoft.kkh.service;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.hlingsoft.kkh.constant.AttachmentConstant;
import com.hlingsoft.kkh.dao.AttachmentDao;
import com.hlingsoft.kkh.entity.Attachment;
import com.hlingsoft.kkh.entity.vo.AttachmentVo;
import com.hlingsoft.kkh.entity.vo.PageVo;
import com.hlingsoft.kkh.exception.UploadException;
import com.hlingsoft.kkh.util.Common;
import com.hlingsoft.kkh.util.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class AttachmentService {

	@Autowired
	private AttachmentDao attachmentDao;

	/*
	 * 上传附件
	 */
	@CacheEvict(value = "article", allEntries = true)
	public Attachment addUploadFile(MultipartFile multipartFile,
									String fileName, long kindId, AttachmentConstant.Kind kind,
									AttachmentConstant.Status status) throws IllegalStateException,
			IOException, UploadException {
		AttachmentConstant.Type type = AttachmentConstant.Type.photo;
		if (UploadUtils.isFileType(fileName, UploadUtils.PHOTO_TYPE)) {
			type = AttachmentConstant.Type.photo;
		} else if (UploadUtils.isFileType(fileName, UploadUtils.FILE_TYPE)) {
			type = AttachmentConstant.Type.file;
		} else {
			throw new UploadException("文件类型有误");
		}
		SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = simpleFormat.format(new Date());
		String fileName1 = System.currentTimeMillis() + "_"
				+ multipartFile.getOriginalFilename();
		putObject(dateString, fileName, multipartFile.getInputStream(),
				multipartFile.getSize());
		System.out.println(fileName1);
		Date now = new Date();
		String uploadPath = UploadUtils.getUploadPath(fileName, now.getTime());
		Attachment attachment = new Attachment();
		attachment.setKindId(kindId);
		attachment.setDescription("");
		attachment.setName(fileName);
		attachment.setType(type);

		attachment.setSize(multipartFile.getSize());
		attachment.setKind(kind);
		attachment.setStatus(status);
		attachment.setCreateTime(now);
		attachment.setLink(dateString + "/" + fileName);
		attachment
//				.setPath("http://dlg.oss-cn-hangzhou.aliyuncs.com/upload/"
				.setPath("http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/"
						+ dateString + "/" + fileName);
		attachmentDao.addAttachment(attachment);



		return attachment;
	}

	/*
	 * etimages
	 */
	public void putObject(String date, String filename, InputStream content,
						  Long size) throws FileNotFoundException {

		// 初始化OSSClient
		OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
				"h7NoXlxcjCqyeOWeuT43LungGmGRSd");


		// 获取指定文件的输入流
		// File file = new File(filePath);
		// InputStream content = new FileInputStream(file);

		// 创建上传Object的Metadata
		ObjectMetadata meta = new ObjectMetadata();

		// 必须设置ContentLength
		meta.setContentLength(size);

		// 上传Object.
		PutObjectResult result = client.putObject("kkh", "upload/" + date
				+ "/" + filename, content, meta);

		// 打印ETag
		System.out.println(result.getETag());
	}



	public boolean checkPhotoFile(MultipartFile file) {
		if (file.isEmpty()) {
			return false;
		}
		if (file.getContentType().equals("image/jpg")
				|| file.getContentType().equals("image/png")
				|| file.getContentType().equals("image/jpeg")
				|| file.getContentType().equals("image/gif")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 *
	 * 删除附件通过附件ID
	 */
	@CacheEvict(value = "article", allEntries = true)
	public void deleteAttachment(long attachmentId, String path) {
		attachmentDao.deleteAttachment(attachmentId);
		UploadUtils.deleteFile(path);
	}

	/**
	 * @param attachmentId
	 * @param status
	 * @return
	 */
	@CacheEvict(value = "article", allEntries = true)
	public boolean updateStatusByAttachmentId(long attachmentId,
											  AttachmentConstant.Status status) {
		attachmentDao.updateStatusByAttachmentId(attachmentId, status);
		return true;

	}

	/**
	 * @param attachmentId
	 * @return
	 */
	public Attachment getAttachmentById(long attachmentId) {
		return attachmentDao.getAttachmentById(attachmentId);
	}

	/**
	 * @param attachmentId
	 * @param link
	 * @return
	 */
	@CacheEvict(value = "article", allEntries = true)
	public int updateLinkByAttachmentId(long attachmentId, String link) {
		return attachmentDao.updateLinkByAttachmentId(attachmentId, link);
	}

	/**
	 * @return
	 */
	@Cacheable(value = "article", key = "'getAttachmentPageByFolderId_'+#kindId+'_'+#kind+'_'+#status+'_'+#pageNum")
	public PageVo<AttachmentVo> getAttachmentPageByKindId(long kindId,
														  AttachmentConstant.Kind kind, int rows, int pageNum) {
		PageVo<AttachmentVo> pageVo = new PageVo<AttachmentVo>(pageNum);
		pageVo.setRows(rows);
		pageVo.setCount(attachmentDao.getAttachmentCountByKindId(kindId, kind,
				AttachmentConstant.Status.display));
		pageVo.setList(attachmentDao.getAttachmentListByKindId(kindId, kind,
				AttachmentConstant.Status.display, pageVo.getOffset(),
				pageVo.getRows()));
		return pageVo;
	}

	/**
	 * @param kindId
	 * @param kind
	 * @param status
	 * @return
	 */
	@Cacheable(value = "article", key = "'getAttachmentListByKindId_'+#kindId+'_'+#kind+'_'+#status")
	public List<AttachmentVo> getAttachmentListByKindId(long kindId,
														AttachmentConstant.Kind kind, AttachmentConstant.Status status) {
		return attachmentDao.getAttachmentListByKindId(kindId, kind, status, 0,
				1000);

	}
}
